<?php

/**
 * Description of Handler
 *
 * @author prometheus
 */
class ExtJS_MultiState_Handler extends x10_GeneralClass
{
	protected $uid;

	/**
	 * @var XDS_DataSource
	 */
	protected $ds;

	public function __construct(x10_Config $config)
	{
		parent::__construct($config);

		$this->uid = $config->getConfigKey('uid');
		$this->ds = $config->getConfigKey('ds');
	}

	public function get($what)
	{
		$result = $this->ds->execute('getList', array($this->pkData($what)))->get();
		if (is_array($result) and count($result) > 0)
		{
			$result = $result[0];
		}
		return $result->get();
	}

	public function getList()
	{
		$resultProv = $this->ds->execute('getList', array(array('idUser'=>$this->uid)));
		$result = NULL;
		if (is_object($resultProv)) $result = $resultProv->get();
		return is_array($result)? $result : array();
	}

	public function set($what)
	{
		$resultProv = $this->ds->execute('getList', array($this->pkData($what['idState'])));
		$exists = FALSE;
		if (!is_null($resultProv))
		{
			$result = $resultProv->get();
			if (is_array($result) and count($result) > 0)
			{
				$exists = TRUE;
			}
		}

		if ($exists)
		{
			$rs = $this->ds->getRecordSet();
			$rs[$rs->getRowIdByPK($this->pkData($what['idState']))] = $what;
			$this->ds->save();
		}
		else
		{
			$rs = $this->ds->getRecordSet();
			$rs[] = $what;
			$this->ds->save();
		}
	}

	protected function pkData($what)
	{
		return array(
			'idUser'	=> $this->uid,
			'idState'	=> $what
		);
	}
}

?>